package cn.com.common.job.task;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasForewarningDataEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStationinfoForecastMonthEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasForewarningDataService;
import cn.com.gas.service.GasStationinfoForecastMonthService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasForewarningDataProcessTask")
@DisallowConcurrentExecution
// @Transactional
public class GasForewarningDataProcessTask {

	@Value("${gasstation.timedTask.gasForewarningDataProcessTask}")
	private String gasForewarningDataProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SysParameterService sysParameterService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasForewarningDataService gasForewarningDataService;
	
	@Autowired
	private GasStationinfoForecastMonthService gasStationinfoForecastMonthService;
	
	public void run(String params) throws Exception {
		// TODO 增加一个重新加工的逻辑

		logger.debug("application参数为gasForewarningDataProcessTask：{}", gasForewarningDataProcessTask);

		if (gasForewarningDataProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasForewarningDataProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasForewarningDataProcessTask定时任务");
		} else {
			// YYYYMMDD_YYYYMMDD 格式
			if (TsBqUtils.isNotNull(params)) {
				String[] _paramsArr = params.split("_");

				for (String _params : _paramsArr) {

					String _year = _params.substring(0, 4);
					String _month = _params.substring(4, 6);
					String _day = _params.substring(6, 8);

					logger.debug("gasForewarningDataProcessTask定时任务正在执行，加工日期：{}", _params);
					handleData(getLastYearMonth(_year, _month), _year + "-" + _month + "-" + _day);
					logger.debug("gasForewarningDataProcessTask定时任务正在执行，加工完成：{}", _params);

				}

			} else {
				// 获取上一个月
				LocalDate now = LocalDate.now(); // 获取当前日期

				LocalDate lastMonth = now.minusMonths(1); // 减去一个月
				String pattern = "yyyyMM"; // 设置输出格式
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
				String format = lastMonth.format(formatter);
				// 获取昨天日期
				Calendar calendar = Calendar.getInstance(); // 创建Calendar实例
				calendar.add(Calendar.DAY_OF_YEAR, -1); // 减去1天
				Date yesterday = calendar.getTime(); // 获取昨天的日期
				SimpleDateFormat _formatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
				String yesterdayStr = _formatter.format(yesterday); // 格式化昨天的日期
				logger.debug("gasForewarningDataProcessTask定时任务正在执行，加工日期：{}", yesterdayStr);
				handleData(format, yesterdayStr);
				logger.debug("gasForewarningDataProcessTask定时任务正在执行，加工完成：{}", yesterdayStr);

			}
		}

	}

	// 上一年月 日期
	private String handleData(String format, String yesterdayStr) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		// 获取参数
		BigDecimal bigDecimal = new BigDecimal("1.3");
		SysParameterEntity parameterEntity = sysParameterService.getById("parameter105");
		if (TsBqUtils.isNotNull(parameterEntity)) {
			BigDecimal num1 = new BigDecimal("1");
			BigDecimal num2 = new BigDecimal(parameterEntity.getParameter());
			bigDecimal = num1.add(num2);
		}

		// 计算上个月的平均值
		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(GasStationinfoEntity::getType, "group");
		queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
		List<GasStationinfoEntity> records = gasStationinfoService.list(queryWrapper);
		List<GasForewarningDataEntity> listForewarningData = new ArrayList<GasForewarningDataEntity>();

		for (GasStationinfoEntity gasStationinfoEntity : records) {

			// 计算累计金额
			BigDecimal result = new BigDecimal(0);

			String id = gasStationinfoEntity.getId();
			String taxorgcode = gasStationinfoEntity.getTaxorgcode();

			LambdaQueryWrapper<GasStationinfoForecastMonthEntity> queryWrapper1 = Wrappers.lambdaQuery();
			queryWrapper1.eq(GasStationinfoForecastMonthEntity::getStationinfoId, id);
			
			queryWrapper1.eq(GasStationinfoForecastMonthEntity::getTime, format.substring(0, 4) + "-" + format.substring(4, 6));
			
			List<GasStationinfoForecastMonthEntity> list = gasStationinfoForecastMonthService.list(queryWrapper1);

			if (TsBqUtils.isNotNull(list)) {
				// int size = list.size();
				String gatherDay = list.get(0).getGatherDay();
				int size = Integer.parseInt(gatherDay);

				for (GasStationinfoForecastMonthEntity entity : list) {
					String price = entity.getGatherValue();
					
					BigDecimal _price = new BigDecimal(price);
					result = result.add(_price);
				}

				BigDecimal avg = new BigDecimal(0);
				if (result.compareTo(BigDecimal.ZERO) == 0) {
					logger.debug("Divisor cannot be zero:" + id);
				} else {
					avg = result.divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP);
				}

				LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper2 = Wrappers.lambdaQuery();

				queryWrapper2.eq(GasStaytimeResultEntity::getStationId, id);
				
				

				queryWrapper2.ge(GasStaytimeResultEntity::getMessageDisappear, sdf.parse(yesterdayStr + " 00:00:00"));
				queryWrapper2.le(GasStaytimeResultEntity::getMessageDisappear, sdf.parse(yesterdayStr + " 23:59:59"));

				List<GasStaytimeResultEntity> list1 = gasStaytimeResultService.list(queryWrapper2);

				BigDecimal resultDay = new BigDecimal(0);
				for (GasStaytimeResultEntity gasStaytimeResultEntity : list1) {
					String price = gasStaytimeResultEntity.getPrice();
					BigDecimal _price = new BigDecimal(price);
					resultDay = resultDay.add(_price);
				}

				// resultDay 等于 0 ,低于 百分之30
				if (resultDay.compareTo(BigDecimal.ZERO) == 0) {
					// 预警
					GasForewarningDataEntity forewarningData = new GasForewarningDataEntity();
					forewarningData.setCumulativeValue(resultDay.toString());
					forewarningData.setMeanValue(avg.toString());
					forewarningData.setStationinfoId(id);
					forewarningData.setTaxorgcode(taxorgcode);

					listForewarningData.add(forewarningData);

				} else {
					if (avg.compareTo(BigDecimal.ZERO) != 0) {
						BigDecimal multiply = resultDay.multiply(bigDecimal);
						String string = multiply.subtract(avg).toString();
						if (string.contains("-")) {
							// 预警
							GasForewarningDataEntity forewarningData = new GasForewarningDataEntity();
							forewarningData.setCumulativeValue(resultDay.toString());
							forewarningData.setMeanValue(avg.toString());
							forewarningData.setStationinfoId(id);
							forewarningData.setTaxorgcode(taxorgcode);

							listForewarningData.add(forewarningData);
						}
					}
				}

			} else {
				 
				logger.debug("gasForewarningDataProcessTask定时任务正在执行，GasStationinfoForecastMonthEntity为空！");

			}

		}

		if (TsBqUtils.isNotNull(listForewarningData)) {
			for (GasForewarningDataEntity forewarningData : listForewarningData) {

				forewarningData.setDeleted(Constants.DATA_NOT_DELETED);
				forewarningData.setCreateTime(new Date());
				forewarningData.setTime(yesterdayStr);
				forewarningData.setCreateId("sysjob");

				gasForewarningDataService.save(forewarningData);

			}
		}
		return "";
	}

	// 获取上一个年月 YYYYMM
	private static String getLastYearMonth(String year, String month) {
		int yearInt = Integer.parseInt(year);

		String substring = month.substring(0, 1);
		String _substring = month.substring(1, 2);
		if (substring.equals("0")) {
			// 1 - 9
			if (_substring.equals("1")) {
				int _yearInt = yearInt - 1;
				return _yearInt + "12";

			} else {
				int monthInt = Integer.parseInt(_substring);
				int _monthInt = monthInt - 1;
				return year + handleMonth(_monthInt);
			}
		} else {
			// 10 - 12
			int monthInt = Integer.parseInt(month);
			int _monthInt = monthInt - 1;
			return year + handleMonth(_monthInt);
		}
	}

	private static String handleMonth(int month) {
		if (month <= 9) {
			return "0" + month;
		} else {
			return "" + month;
		}
	}

	public static void main(String[] args) {

		// System.out.println(getLastYearMonth("2024", "08"));
		String _params = "20240808";
		String _year = _params.substring(0, 4);
		String _month = _params.substring(4, 6);
		String _day = _params.substring(6, 8);
		
		System.out.println(_year + _month + _day);
	}

}
